from django.shortcuts import render, redirect
from django.urls import reverse

from util.mixin import LoginRequiredMixin

#celery email
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from celery_tasks.tasks import send_email_to_verify

#html_page_str
 #RegisterView,LoginView
register_html = "register.html"
login_html = "login.html"
index_html = "index.html"

 #InfoView, OrderView, SiteView
user_info  = 'user_center_info.html'
user_order = 'user_center_order.html'
user_site  = 'user_center_site.html'

#RegisterView
from django.views.generic import View
from user.models import User, Address

#LoginView, LogOutView
from django.contrib.auth import authenticate, login, logout

#Redis as cache
from django_redis import get_redis_connection

from goods.models import GoodsSKU
class RegisterView(View):
    def get(self, request):
        return render(request, register_html)

    def post(self,request):
        #1.获取数据
        username = request.POST.get("user_name")
        password = request.POST.get("pwd")
        email    = request.POST.get("email")

        #2.校验数据
        if not all((username, password, email)):
            return render(request, register_html, {'errsg':'username/passwd/email is missing'})

        #3.业务处理
        try:
            user = User.objects.get(username = username) #user可能拿不到数据
        except User.DoesNotExist:
            user = None

        if not user:
            user = User.objects.create_user(username, email, password)
            user.is_active = 0
            user.save()

        serialize = Serializer(settings.SECRET_KEY)
        confirm = {'confirm':user.id}
        token = serialize.dumps(confirm) 
        token = token.decode()
        
        send_email_to_verify.delay(email, username, token) #add this
        
        return render(request, login_html)

class LoginView(View):
    def get(self, request):
            if 'username' in request.COOKIES:
                username =  request.COOKIES.get('username')
                checked  = "checked"
            else:
                username = ""
                checked  = ""
    
            return render(request, login_html, {"username":username, "checked":checked})

    def post(self, request):
        #1.获取数据
        username = request.POST.get("username")
        password = request.POST.get("pwd")

        #2.校验数据
        if not all((username, password)):
            return render(request, login_html, {'errmsg':'username/passwd should not be none'})

        user = authenticate(username=username, password = password)
        if user:
            if user.is_active:
                login(request, user)
                remember = request.POST.get('remember') #add all 7 lines
                next_url = request.GET.get('next', reverse("goods:index"))
                res = redirect(next_url) 
                if remember == 'on':
                    res.set_cookie('username', username, 7*24*3600)
                else:
                    res.delete_cookie('username')
                return res
            else:
                return render(request, login_html)
        else:
            return render(request, login_html)

class LogOutView(View):
    def get(self, request):
        logout(request)
        return redirect(reverse("goods:index"))

#/user/info
class InfoView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        address = Address.objects.get_default_address(user)

        con = get_redis_connection("default")
        history_key = 'history_%d'%user.id
        sku_ids = con.lrange(history_key, 0, 4)
        
        print(sku_ids)
        goods_li = []
        for id in sku_ids:
            goods = GoodsSKU.objects.get(id=id)
            goods_li.append(goods)
        return render(request, user_info, {'page':'info', 'address':address, 'goods_li':goods_li})
    
#/user/address
class SiteView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        address = Address.objects.get_default_address(user)
        return render(request, user_site, {'page':'site', 'address':address})

    def post(self, request):
        #1.接收数据
        receiver = request.POST.get('receiver')
        addr = request.POST.get('addr')
        phone = request.POST.get('phone')
        zip_code = request.POST.get('zip_code')
        
        #2.校验
        if not all((receiver, addr, phone)):
            return render(request, user_site, {'errmsg': '数据不完整'})

        #手机号
        #if not re.match(r'^1[3|4|5|6]\d{9}', phone):
        #    return render(request, user_site, {'errmsg': '手机格式不对'})

        #3.业务处理
        user = request.user
        address = Address.objects.get_default_address(user)

        if address:
            is_default = False
        else:
            is_default = True
           
        Address.objects.create(user = user, receiver = receiver, addr = addr, phone_number = phone, zip_code = zip_code, is_default = is_default) 
        return redirect(reverse("user:site"))

class ActiveView(View):
    '''activate user
    '''
    def get(self, request, token):

        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            data = serializer.loads(token)
        except SignatuureExpired as e:
            return HttpResponse('过期')
            
        user_id = data['confirm']
        user = User.objects.get(id=user_id)
        user.is_active = 1
        user.save()
        return render(request, 'login.html')

#/user/order
class OrderView(LoginRequiredMixin,View):
    def get(self, request):
        return render(request, user_order, {'page':'order'})


from django.core.paginator import Paginator
from order.models import OrderInfo,OrderGoods



#/user/order
class OrderView(LoginRequiredMixin,View):
    def get(self, request, page):
        # 获取用户的订单信息
        user = request.user
        orders = OrderInfo.objects.filter(user=user).order_by('-create_time')

        # 遍历获取订单商品的信息
        for order in orders:
            # 根据order_id查询订单商品信息
            order_skus = OrderGoods.objects.filter(order_id=order.order_id)

            # 遍历order_skus计算商品的小计
            for order_sku in order_skus:
                # 计算小计
                amount = order_sku.count*order_sku.price
                # 动态给order_sku增加属性amount,保存订单商品的小计
                order_sku.amount = amount

            # 动态给order增加属性，保存订单状态标题
            order.status_name = OrderInfo.ORDER_STATUS[order.order_status]
            # 动态给order增加属性，保存订单商品的信息
            order.order_skus = order_skus

        # 分页
        paginator = Paginator(orders, 1)

        # 获取第page页的内容
        try:
            page = int(page)
        except Exception as e:
            page = 1

        if page > paginator.num_pages:
            page = 1

        # 获取第page页的Page实例对象
        order_page = paginator.page(page)

        # todo: 进行页码的控制，页面上最多显示5个页码
        # 1.总页数小于5页，页面上显示所有页码
        # 2.如果当前页是前3页，显示1-5页
        # 3.如果当前页是后3页，显示后5页
        # 4.其他情况，显示当前页的前2页，当前页，当前页的后2页
        num_pages = paginator.num_pages
        if num_pages < 5:
            pages = range(1, num_pages + 1)
        elif page <= 3:
            pages = range(1, 6)
        elif num_pages - page <= 2:
            pages = range(num_pages - 4, num_pages + 1)
        else:
            pages = range(page - 2, page + 3)
            
        # 组织上下文
        context = {'order_page':order_page,
                   'pages':pages,
                   'page': 'order'}

        # 使用模板
        return render(request, 'user_center_order.html', context)
